package com.xuecheng.filesystem.service;

import com.alibaba.fastjson.JSON;
import com.xuecheng.filesystem.dao.FileSystemRepository;
import com.xuecheng.framework.domain.filesystem.FileSystem;
import com.xuecheng.framework.domain.filesystem.response.FileSystemCode;
import com.xuecheng.framework.domain.filesystem.response.UploadFileResult;
import com.xuecheng.framework.exception.ExceptionCast;
import com.xuecheng.framework.model.response.CommonCode;
import org.apache.commons.lang3.StringUtils;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * Created by Aniymx on 2018/12/27 15:59.
 */
@Service
public class FileSystemService {
    /**
     * @Description: 上传图片功能
     * @Param: connect_timeout_in_seconds: 5
     * network_timeout_in_seconds: 30
     * charset: UTF-8
     * tracker_servers: 192.168.101.65:22122 #多个 trackerServer中间以逗号分隔
     * @return:
     * @Author: Mr.aniymx
     * @Date:
     */
    /*注入基本的配置信息*/
    @Value("${xuecheng.fastdfs.connect_timeout_in_seconds}")
    int connect_timeout_in_seconds;
    @Value("${xuecheng.fastdfs.charset}")
    String charset;
    @Value("${xuecheng.fastdfs.network_timeout_in_seconds}")
    int network_timeout_in_seconds;
    @Value("${xuecheng.fastdfs.tracker_servers}")
    String tracker_servers;
    @Autowired
    private FileSystemRepository fileSystemRepository;

    /*初始化信息配置*/
    private void initFdfsConfig() {
        try {
            ClientGlobal.initByTrackers(tracker_servers);
            ClientGlobal.setG_charset(charset);
            ClientGlobal.setG_connect_timeout(connect_timeout_in_seconds);
            ClientGlobal.setG_network_timeout(network_timeout_in_seconds);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*上传图片功能*/
    public UploadFileResult upload(MultipartFile multipartFile, String fileTag, String businesskey, String metadata) {
        if (multipartFile==null){
            ExceptionCast.cast(FileSystemCode.FS_UPLOADFILE_FILEISNULL);
        }
        //加载基本配置
        //上传文件到fds
        String fileId = this.fsdf_upload(multipartFile);
        FileSystem fileSystem = new FileSystem();
        fileSystem.setFileId(fileId);
        fileSystem.setFilePath(fileId);
        fileSystem.setFiletag(fileTag);
        fileSystem.setBusinesskey(businesskey);
        if (StringUtils.isNotEmpty(metadata)){
            Map map = JSON.parseObject(metadata, Map.class);
            fileSystem.setMetadata(map);
        }
        //向文件系统中存数据
        fileSystemRepository.save(fileSystem);
        return new  UploadFileResult(CommonCode.SUCCESS,fileSystem);
    }

    /*上传文件到fastdfs*/
    private String fsdf_upload(MultipartFile file) {

        try {
            initFdfsConfig();
            TrackerClient trackerClient = new TrackerClient();
            /*得到连接对象*/
            //得到trackerServer
            TrackerServer trackerServer = trackerClient.getConnection();
            //得到storeStorage
            StorageServer storeStorage = trackerClient.getStoreStorage(trackerServer);
            //使用storageClient1对象进行文件的上传
            StorageClient1 storageClient1 = new StorageClient1();
            //得到文件对象信息
            byte[] bytes = file.getBytes();
            //得到文件的文件名
            String originalFilename = file.getOriginalFilename();
            //得到文件的扩展名
            String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            String fileId = storageClient1.upload_file1(bytes, substring, null);
            return fileId;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
